/**
 * 基础菜单 产品信息
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.proName" placeholder="输入产品名称"></el-input>
      </el-form-item>
      <el-form-item size="small" label="产品类型">
          <el-select clearable size='mini' v-model="formInline.productType" placeholder="请选择产品类型" autocomplete="off"
                     style="width: 100%">
            <el-option v-for="item in dictProType" :key="item.typeName" :label="item.typeName" :value="item.no">
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small"  type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="photo" label="产品照片"  width="130">
          <!-- 图片的显示 -->
          <template slot-scope="scope">            
            <img :src="scope.row.photo"  width="100" height="100" />
          </template>
      </el-table-column>
      <el-table-column sortable prop="proName" label="产品名称" width="300">
      </el-table-column>
      <el-table-column sortable prop="productType" label="产品类型" width="300">
      </el-table-column>
       <el-table-column sortable prop="descri" label="描述" width="300">
      </el-table-column>
      <el-table-column sortable prop="amount" label="单价" width="300">
      </el-table-column>
      <el-table-column sortable prop="status" label="状态" width="300">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="success" :disabled='scope.row.status_ori != 1' @click="showProduct(scope.$index, scope.row)">上架</el-button>
          <el-button size="mini" type="danger" :disabled="scope.row.status_ori != 0" @click="hideProduct(scope.$index, scope.row)">下架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="50%" @click="closeDialog">
     <el-form label-width="100px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="产品名称" prop="proName">
          <el-input size="small" v-model="editForm.proName" auto-complete="off"></el-input>
        </el-form-item>
         <el-form-item size="small" label="产品类型" prop="productType">
          <el-select clearable size='mini' v-model="editForm.productType" placeholder="请选择产品类型" autocomplete="off"
                     style="width: 100%">
            <el-option v-for="item in dictProType" :key="item.typeName" :label="item.typeName" :value="item.no">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="amount">
          <el-input size="small" v-model="editForm.amount" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descri">
          <el-input size="small" v-model="editForm.descri" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品头像" prop="photo">
           <el-upload class="upload-demo"
            action="上传的地址"
            list-type="picture-card"
            :limit='1'
            :on-remove='handleRmove'
            :on-change="imageChange"
            :auto-upload="false"
            :file-list="fileList"
            ref="upload"
            accept=".jpg, .jpeg, .png"
            >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率256*256)</div>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { productList, productUpdate, productSave,productDel,productTypeList,productShow,productHide } from '../../api/productMG'
import Pagination from '../../components/Pagination'
import { objectToFormData } from 'object-to-formdata';
import { base64ToArrayBuffer} from '../../utils/util'


export default {
  data() {
    return {
      sellerNo:'',
      dictProType:[],
      fileList:[],
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        no:'',
        productType:'',
        proName:'',
        amount:'',
        descri:'',
        sellerNo:''
      },
      // rules表单验证
      rules: {
        proName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        productType: [{ required: true, message: '请输入商品类型', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
      },
       formInline: {
        pageIndex: 1,
        pageSize: 10,
        productType:null,
        proName:null,
        sellerNo: localStorage.getItem('sellerNo'),
      },
      // 删除部门
      seletedata: {
        ids: ''
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.sellerNo = localStorage.getItem('sellerNo1');
    this.getdata(this.formInline);
  },
  mounted(){
    let parameter = {
      sellerNo:localStorage.getItem("sellerNo")
    }
    productTypeList(parameter)
        .then(res => {
          this.loading = false
          if (res.success == '0') {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.dictProType = res.data.datas
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('产品类型加载失败，请稍后再试！')
        })
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
     imageChange(file, fileList, name) {//on-change触发
        this.fileList = fileList
      },
      handleRmove(file,fileList,name){
        this.fileList = []
      },
   
    // 获取公司列表
    getdata(parameter) {
      this.loading = true
      // 模拟数据结束

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      productList(parameter)
        .then(res => {
          this.loading = false
          if (res.success == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            for(let i = 0;i<res.data.datas.length;i++){
              res.data.datas[i].photo = 'data:image/png;base64,'+res.data.datas[i].photo;
            }
            this.listData = res.data.datas
            // 分页赋值
            this.pageparm.currentPage = this.formInline.pageIndex
            this.pageparm.pageSize = this.formInline.pageSize
            this.pageparm.total = res.data.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('产品类型加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.pageIndex = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline)
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.fileList = [];
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.proName = row.proName
        this.editForm.productType = row.productType_ori
        this.editForm.amount = row.amount
        this.editForm.descri = row.descri
        this.editForm.no = row.no
        this.editForm.sellerNo = row.sellerNo
        let obj = new Object();
        obj.url = row.photo;
        let bytes = [];
        bytes.push(base64ToArrayBuffer(row.photo));
        let file = new File(bytes,"photo.png",null)
        obj.raw = file
        this.fileList.push(obj)
      } else {
        this.title = '添加'
        this.editForm.proName = ''
        this.editForm.productType = ''
        this.editForm.amount = ''
        this.editForm.descri = ''
        this.editForm.no = ''
        this.editForm.sellerNo = localStorage.getItem('sellerNo')
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      if(this.fileList.length < 1){
        this.$message.error('请上传商品头像！')
        return false;
      }
      this.$refs[editData].validate(valid => {
        if (valid) {
            let formData = objectToFormData(this.editForm);
              for(let i = 0;i<this.fileList.length;i++){
                formData.append("photo"+i,this.fileList[i].raw);
              }
           if(this.editForm.no == ''){
              productSave(formData)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              if (res.code == '1') {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '产品保存成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('产品保存失败，请稍后再试！')
            })
          }else{
            productUpdate(formData)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              if (res.code == '1') {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '产品更新成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('产品更新失败，请稍后再试！')
            })
          }
        } else {
          return false
        }
      })
    },
    // 删除商品
    deleteUser(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let param = {
            no:row.no
          }
          productDel(param)
            .then(res => {
              if (res.code == '1') {
                this.$message({
                  type: 'success',
                  message: '商品已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('商品删除失败，请稍后再试！')
            })
        })
    },
    // 上架商品
    showProduct(index, row) {
      this.$confirm('确定要上架吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let param = {
            no:row.no
          }
          productShow(param)
            .then(res => {
              if (res.code == '1') {
                this.$message({
                  type: 'success',
                  message: '商品已上架!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('商品上架失败，请稍后再试！')
            })
        })
    },
    // 下架商品
    hideProduct(index, row) {
      this.$confirm('确定要下架吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let param = {
            no:row.no
          }
          productHide(param)
            .then(res => {
              if (res.code == '1') {
                this.$message({
                  type: 'success',
                  message: '商品已下架!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('商品下架失败，请稍后再试！')
            })
        })
    }
    ,
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 